# 1.引入pymongo的MongoClient
from pymongo import MongoClient
# 引入src.setting里面的DATABASE
from src.setting import DATABASE
# 2. 创建Model类
class Model:
# 3. Model类里面添加连接信息
    def __init__(self):
        try:
            self._client = MongoClient(DATABASE['mongodb']['HOST'], DATABASE['mongodb']['PORT'])
            self._db = self._client[DATABASE['mongodb']['DATABASE']]
        except:
            return "服务器出错"
    def try_ex(self,func):
        try:
           return func
        except Exception as Err:
            raise Exception(Err)
# 4. 创建User类
class User(Model):
    def __init__(self):
        Model.__init__(self)
        self._col=self._db['user']
# 5. User类里面完成user集合的CRUD
# 对于用户来说，账号名不能相同
    def insert(self,data):
        if not data['user']:
            raise ValueError("没有账号名")
        elif self._col.count_documents({"user":data['user']})>0:
            raise ValueError("已有该账户名") 
        return self.try_ex(self._col.insert_one(data).inserted_id)
        # return self._col.insert_one(data).inserted_id

    def find(self,query=None):
        return self._col.find(query) 

from gridfs import GridFS
import time
import random
import os
import io
from bson import ObjectId
class Video(Model):
    def __init__(self):
        Model.__init__(self)
        self._col=self._db['video']
        self._fs = GridFS(self._db)
    # 将文件名改为时间戳+四位随机数+后缀名
    def _getFileName(self,fname):
        timestamp = int(time.time())
        randNum = random.randint(1000,9999)
        base,extension = os.path.splitext(fname)
        return f'{timestamp}{randNum}{extension}'

    # 上传文件到GridFS上，返回file_id
    def insertFile(self,vfile):
        try:
            vfilename = self._getFileName(vfile.filename)
            vstream = io.BytesIO(vfile.read()) # 将文件读取为流，方便上传
            # 类比
            # with open(file_path,'rb') as fileObj:
            file_id = self._fs.put(vstream,filename=vfilename)
            return file_id
        except Exception as err:
            raise Exception(err)

    # 上传包含file_id的视频相关信息的，返回video_id
    def insertDoc(self,doc):
        return self.try_ex(self._col.insert_one(doc).inserted_id)
        ''' 
        try:
            return self._col.insert_one(doc).inserted_id
        except Exception as err:
            raise Exception(err)
        '''
    def find(self,query=None):
        return self.try_ex(list(self._col.find(query)))

    def getVideo(self,fileid):
        video_file = self._fs.get(ObjectId(fileid))  
        if video_file:  
            return video_file 
        else:  
            raise ValueError('没有该视频')
            
    def delDoc(self,query):
        try:
            videos = self._col.find(query)
            video =list(videos)[0]
            self._fs.delete(video['vfileid']) # 删除视频
            self._fs.delete(video['vimgid']) # 删除图片
            self._col.delete_one(query)
        except Exception as err:
            raise ValueError(str(err))

# 实例化所有的对象，方便后面调用
user = User()
videoModel = Video()